using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.Extend.Dtos.ProjectGantt;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 项目计划
    /// 版 本：V2.6.200509
    /// 版 权：引迈信息技术有限公司（https://www.yinmaisoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-11-16 
    /// </summary>
    [Route("api/Extend/[controller]")]
    public class ProjectGanttController : BaseApiController
    {
        private ProjectGanttBll projectGanttBll = new ProjectGanttBll();
        private UserBll userBll = new UserBll();

        #region GET
        /// <summary>
        /// 项目列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList([FromQuery] KeywordInput input)
        {
            var data = await projectGanttBll.GetList();
            if (!input.keyword.IsNullOrEmpty())
            {
                data = data.FindAll(x => x.FullName.Contains(input.keyword));
            }
            var output = data.MapToList<ProjectGanttListOutput>();
            await GetManagersInfo(output);
            return Success(new { list = output });
        }

        /// <summary>
        /// 任务列表
        /// </summary>
        /// <param name="projectId">项目Id</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("{projectId}/Task")]
        public async Task<ResponseResult> GetTaskList([FromQuery] KeywordInput input, string projectId)
        {
            var data = await projectGanttBll.GetTaskList(projectId);
            if (!string.IsNullOrEmpty(input.keyword))
            {
                data = data.TreeWhere(t => t.FullName.Contains(input.keyword), t => t.Id, t => t.ParentId);
            }
            var output = data.MapToList<ProjectGanttTaskListOutput>();
            return Success(new { list = output.ToTree() });
        }

        /// <summary>
        /// 任务树形
        /// </summary>
        /// <param name="projectId">项目Id</param>
        /// <returns></returns>
        [HttpGet("{projectId}/Task/Selector")]
        public async Task<ResponseResult> GetTaskTreeView(string projectId)
        {
            var data = (await projectGanttBll.GetTaskList(projectId)).MapToList<ProjectGanttTaskTreeViewOutput>();
            return Success(new { list = data.ToTree() });
        }

        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var data = (await projectGanttBll.GetInfo(id)).MapTo<ProjectGanttInfoOutput>();
            return Success(data);
        }

        /// <summary>
        /// 项目任务信息
        /// </summary>
        /// <param name="taskId">主键值</param>
        /// <returns></returns>
        [HttpGet("Task/{taskId}")]
        public async Task<ResponseResult> GetTaskInfo(string taskId)
        {
            var data = (await projectGanttBll.GetInfo(taskId)).MapTo<ProjectGanttTaskInfoOutput>();
            return Success(data);
        }
        #endregion

        #region POST
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            if (await projectGanttBll.AllowDelete(id))
            {
                var entity = await projectGanttBll.GetInfo(id);
                if (entity != null)
                {
                    await projectGanttBll.Delete(entity);
                }
                return Success("删除成功");
            }
            else
            {
                return Error("此记录被关联引用,不允许被删除");
            }
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Create([FromBody] ProjectGanttCrInput input)
        {
            if (await projectGanttBll.IsExistByEnCode(input.enCode, null))
            {
                return Error("编码已存在");
            }
            if (await projectGanttBll.IsExistByFullName(input.fullName, null))
            {
                return Error("名称已存在");
            }
            var entity = input.MapTo<ProjectGanttEntity>();
            entity.Type = 1;
            entity.ParentId = "0";
            await projectGanttBll.Create(entity);
            return Success("创建成功");
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update(string id, [FromBody] ProjectGanttUpInput input)
        {
            if (await projectGanttBll.IsExistByEnCode(input.enCode, id))
            {
                return Error("编码已存在");
            }
            if (await projectGanttBll.IsExistByFullName(input.fullName, id))
            {
                return Error("名称已存在");
            }
            var entity = input.MapTo<ProjectGanttEntity>();
            await projectGanttBll.Update(id, entity);
            return Success("更新成功");
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPost("Task")]
        public async Task<ResponseResult> CreateTask([FromBody] ProjectGanttTaskCrInput input)
        {
            var entity = input.MapTo<ProjectGanttEntity>();
            entity.Type = 2;
            await projectGanttBll.Create(entity);
            return Success("创建成功");
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPut("Task/{id}")]
        public async Task<ResponseResult> UpdateTask(string id, [FromBody] ProjectGanttTaskUpInput input)
        {
            var entity = input.MapTo<ProjectGanttEntity>();
            await projectGanttBll.Update(id, entity);
            return Success("更新成功");
        }
        #endregion

        #region Method
        /// <summary>
        /// 项目参与人员
        /// </summary>
        /// <param name="outputList"></param>
        /// <returns></returns>
        private async Task GetManagersInfo(List<ProjectGanttListOutput> outputList)
        {
            var userList = await userBll.GetList();
            foreach (var output in outputList)
            {
                List<string> managerIds = new List<string>(output.managerIds.Split(","));
                foreach (var id in managerIds)
                {
                    var managerInfo = new ManagersInfo();
                    var userInfo = userList.Find(x => x.Id == id);
                    if (userInfo != null)
                    {
                        managerInfo.account = userInfo.RealName + "/" + userInfo.Account;
                        managerInfo.headIcon = string.IsNullOrEmpty(userInfo.HeadIcon) ? "" : "/api/Common/Image/userAvatar/" + userInfo.HeadIcon;
                        output.managersInfo.Add(managerInfo);
                    }
                }
            }
        }
        #endregion
    }
}
